/**
 * HTTP 请求封装
 */

import { API_CONFIG } from './config'

export interface RequestOptions extends RequestInit {
  params?: Record<string, string | number>
}

/**
 * 通用请求函数
 */
export async function request<T>(url: string, options?: RequestOptions): Promise<T> {
  try {
    // 处理 URL 参数
    let finalUrl = `${API_CONFIG.baseURL}${url}`
    if (options?.params) {
      const searchParams = new URLSearchParams()
      Object.entries(options.params).forEach(([key, value]) => {
        searchParams.append(key, String(value))
      })
      finalUrl += `?${searchParams.toString()}`
    }

    const response = await fetch(finalUrl, {
      ...options,
      headers: {
        ...API_CONFIG.headers,
        ...options?.headers,
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 如果是 DELETE 请求，可能没有响应体
    if (options?.method === 'DELETE') {
      return null as T
    }

    return await response.json()
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

/**
 * GET 请求
 */
export async function get<T>(url: string, params?: Record<string, string | number>): Promise<T> {
  return request<T>(url, { method: 'GET', params })
}

/**
 * POST 请求
 */
export async function post<T>(url: string, data?: unknown): Promise<T> {
  return request<T>(url, {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

/**
 * PATCH 请求
 */
export async function patch<T>(url: string, data?: unknown): Promise<T> {
  return request<T>(url, {
    method: 'PATCH',
    body: JSON.stringify(data),
  })
}

/**
 * PUT 请求
 */
export async function put<T>(url: string, data?: unknown): Promise<T> {
  return request<T>(url, {
    method: 'PUT',
    body: JSON.stringify(data),
  })
}

/**
 * DELETE 请求
 */
export async function del<T = void>(url: string): Promise<T> {
  return request<T>(url, { method: 'DELETE' })
}
